import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/const/MahjongConst.dart';
import 'package:mahjong/const/MahjongSystemConst.dart';
import 'package:mahjong/entity/MessageContext.dart';
import 'package:mahjong/entity/mahjong/MahjongInfoEntity.dart';
import 'package:mahjong/notify/CurrentUserInfo.dart';
import 'package:provider/provider.dart';
import 'package:rive/rive.dart';

class DiceWidget extends StatefulWidget {
  @override
  _DiceWidgetState createState() => _DiceWidgetState();
}

class _DiceWidgetState extends State<DiceWidget> with TickerProviderStateMixin {
  int dice = 1;
  Timer diceTimer;
  bool showChangeView = false;
  Animation animation;
  AnimationController controller;
  bool reading = false;
  Artboard _riveArtboard;
  RiveAnimationController _controller;
  String changeView;
  @override
  void initState() {
    super.initState();
    rootBundle.load('assets/rive/mahjong/swapcard.riv').then(
      (data) async {
        final file = RiveFile.import(data);
        _riveArtboard = file.mainArtboard;
      },
    );
    reading = true;
    // 监听
    diceStreamController.stream.listen((event) {
      MessageContext messageContext = event as MessageContext;
      if (messageContext.action == MessageAction.DISK_DICE &&
          messageContext.body != null &&
          messageContext.body.toString().length > 0) {
        this.controller = AnimationController(
            duration: const Duration(milliseconds: 1000), vsync: this);
        var mahjongInfo = Provider.of<MahjongInfoEntity>(
            navigatorKey.currentContext,
            listen: false);
        int diceNumber = messageContext.body;

        if (mahjongInfo.rule.userCount == 2) {
          changeView = 'btchange';
        } else if (mahjongInfo.rule.userCount == 3) {
          if (diceNumber % 2 == 0) {
            changeView = 'lrchange';
          } else {
            changeView = 'rlchange';
          }
        } else if (mahjongInfo.rule.userCount == 4) {
          if (diceNumber == 2 || diceNumber == 6) {
            changeView = 'btchange';
          } else if (diceNumber == 1 || diceNumber == 5) {
            changeView = 'rlchange';
          } else if (diceNumber == 3 || diceNumber == 4) {
            changeView = 'lrchange';
          }
        }
        _controller = SimpleAnimation(changeView);
        _riveArtboard.removeController(_controller);
        _riveArtboard.addController(_controller);
        final CurvedAnimation curve =
            CurvedAnimation(parent: controller, curve: Curves.easeIn);
        animation = Tween(
                begin: ScreenUtil().screenHeight / 2 +
                    MahjongSystemConst.diceSize / 2 * 2,
                end: ScreenUtil().screenHeight / 2 -
                    MahjongSystemConst.diceSize / 2)
            .animate(curve);
        controller.forward();
        diceTimer = new Timer.periodic(new Duration(milliseconds: 17),
            (Timer timer) async {
          dice = new Random().nextInt(9) + 1;
          setState(() {});
        });
        controller.addListener(() {
          if (controller.isCompleted) {
            diceTimer.cancel();
            dice = messageContext.body;
            showChangeView = true;
            setState(() {});
            Future.delayed(Duration(seconds: 2), () {
              setState(() {
                var currentUserInfo = Provider.of<CurrentUserInfo>(
                    navigatorKey.currentContext,
                    listen: false);
                currentUserInfo.swapAfter();
                showChangeView = false;
              });
            });
          }
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _riveArtboard.remove();
    if (diceTimer != null && diceTimer.isActive) {
      diceTimer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (BuildContext buildContext,
        MahjongInfoEntity roomProvider, Widget child) {
      if (roomProvider.exchangeValue != null) {
        return buildSwapWidget(
            roomProvider.exchangeValue,
            ScreenUtil().screenHeight / 2 - MahjongSystemConst.diceSize / 2,
            showChangeView);
      } else {
        return reading && animation != null
            ? buildSwapWidget(dice, animation.value, showChangeView)
            : SizedBox();
      }
    });
  }

  Stack buildSwapWidget(int diceValue, double top, bool showChangeView) {
    return Stack(children: [
      showChangeView && changeView != null
          ? Align(
              alignment: Alignment(0, 0.5),
              child: AnimatedContainer(
                  duration: Duration(seconds: 2),
                  height: ScreenUtil().screenHeight / 3,
                  width: ScreenUtil().screenHeight / 3,
                  child: Rive(artboard: _riveArtboard)))
          : Container(),
      Positioned(
          top: top,
          left: ScreenUtil().screenWidth / 2 - MahjongSystemConst.diceSize / 2,
          child: Container(
              width: MahjongSystemConst.diceSize,
              height: MahjongSystemConst.diceSize,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Image.asset(
                  "images/mahjong/dice/dice" + diceValue.toString() + ".png",
                  fit: BoxFit.fill,
                ),
              )))
    ]);
  }
}
